/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.meraklisina.latexeditor.mdi.Common;

import java.io.*;
import javax.swing.JOptionPane;
import javax.swing.JTextPane;

import com.meraklisina.latexeditor.mdi.Pane.SweTextPane;


/**
 *
 * @author Eray
 */
public class FileOperations
{
    /**
     * Gets the <b>called</b> project's physical startup path.
     *
     * @return Projects StartupPath
     */
    public String GetStartupPath()
    {
        String startupPath = "";

        try
        {
            startupPath = (new File (".")).getCanonicalPath();

//            if(startupPath.contains(" "))
//                JOptionPane.showMessageDialog(null,"\nThis application path's contains blank spaces." +
//                                                            "\nThe spaces inside the path will cause problems building the files with MiKTeX." +
//                                                            "\nPlease  use this application in a path that does not contain spaces  (Ex: C:\\ )","File Path Warning",JOptionPane.WARNING_MESSAGE);
        }
        catch (IOException ex)
        {
            JOptionPane.showMessageDialog(null,"Cannot get startup path! : " + ex.getMessage(),"File error",JOptionPane.ERROR_MESSAGE);
        }
        return startupPath + "\\";
    }
    /**
     * Checks if the specified file exists. If not, it informs
     * with a Message Dialog.
     *
     * @param FilePath
     * @return
     */
    public boolean IsFileExists(String FilePath)
    {
        File file = new File(FilePath);
        if(!file.exists())
        {
            JOptionPane.showMessageDialog(null,"File does not exists! Please make sure '" + FilePath + "' exists", "Wrong Path",JOptionPane.ERROR_MESSAGE);
            return false;
        }
        else
            return true;
    }
    /**
     * This functions should be used when you are opening a text file into your
     * application. It reads the text from the file and writes it on your text
     * component.
     *
     *
     * @param file
     * @return Text from the read file
     */
    public String ReadFileGetText(File file)
    {
        String Result = "";

        try
        {
              BufferedReader br = new BufferedReader(new FileReader(file));
              String s=""; int c=0;
              while((c=br.read())!=-1) s+=(char)c;

              br.close();
              Result = s;
          }
        catch (Exception ex)
        { JOptionPane.showMessageDialog(null,"Cannot open file!" + ex.getMessage(),"File error",JOptionPane.ERROR_MESSAGE);}

        return Result;
    }
    /**
     * Tries to execute the command line you specify and waits for the process
     * if it is necessary.
     *
     * @param command
     * @param wait
     * @return Process
     * @throws java.io.IOException
     */
    public static Process Exec ( String command, boolean wait ) throws IOException
    {
        Process p;
        try
      {
      p = Runtime.getRuntime().exec( command );
      }
        catch ( IOException e )
      {
      return null;
      }
        if ( wait )
      {
      try
         {
         //p.waitFor();
          p.wait(5000);
         }
      catch ( InterruptedException e )
         {
         Thread.currentThread().interrupt();
         }
      }
      // You must close these even if you never use them!
       p.getInputStream().close();
       p.getOutputStream().close();
       p.getErrorStream().close();
       return p;
    } // end exec
    /**
     * Deletes the specifed file. The file's path can both be physical or
     * relative.
     *
     * @param FilePath
     * @throws java.io.IllegalArgumentException
     */
    public void DeleteFile(String FilePath)
    {
        File file = new File(FilePath);

        String fileName = file.getName();
        // A File object to represent the filename

        // Make sure the file or directory exists and isn't write protected
        if (!file.exists())
          throw new IllegalArgumentException(
              "Delete: no such file or directory: " + fileName);

        if (!file.canWrite())
          throw new IllegalArgumentException("Delete: write protected: "
              + fileName);

        // If it is a directory, make sure it is empty
        if (file.isDirectory()) {
          String[] files = file.list();
          if (files.length > 0)
            throw new IllegalArgumentException(
                "Delete: directory not empty: " + fileName);
        }

        // Attempt to delete it
        boolean success = file.delete();

        if (!success)
          throw new IllegalArgumentException("Delete: deletion failed");

    }
    /**
     * Extracts and returns the extention of a given file name.
     *
     * @param filename
     * @return Extension of the specifed file
     */
    public String GetFileExtension(String filename)
    {
        String ext = filename.substring(filename.lastIndexOf('.')+1, filename.length());

        if(filename.lastIndexOf('.') == 0)
            ext = "";

        return ext;
    }
    /**
     * Extracts and returns the extention of a given file object.
     *
     * @param file
     * @return Extension of the specifed file
     */
    public String GetFileExtension(File file)
    {
        String filename = file.getName();
        String ext = filename.substring(filename.lastIndexOf('.')+1, filename.length());

        if(filename.lastIndexOf('.') <= -1)
            ext = "";

        return ext;
    }
    /**
     * This function is intented to help during <b>Save</b> operations.
     * When a user types a file name from the SaveDialog, he/she may not
     * specify the required <b>file extension</b> correctly or he/she
     * may not type the extension at all. So, the given file is checked
     * with the given file extension and if it is not it is supposed
     * to be, this function fixes it.
     *
     * @param file
     * @param Extension
     * @return File object
     */
    public File HandleExtension(File file, String Extension)
    {
        Extension = Extension.toLowerCase();

        if(GetFileExtension(file).isEmpty() || !GetFileExtension(file).equals(Extension))
            file = new File(file.getPath() + "." + Extension);

        return file;
    }
    /**
     * Copies a specifed source File object to a specifed destination
     * File object.
     *
     * @param src
     * @param dst
     * @throws java.io.IOException
     */
    public void CopyFile(File src, File dst) throws IOException
    {
        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(dst);

        // Transfer bytes from in to out
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }
    /**
     * Eliminates the file's name's extension and returns it.
     *
     * @param fileName
     * @return File's name without it's extension.
     */
    public String GetFileNameWithoutExtension(String fileName)
    {
        File tmpFile = new File(fileName);
        tmpFile.getName();
        int whereDot = tmpFile.getName().lastIndexOf('.');
        if (0 < whereDot && whereDot <= tmpFile.getName().length() - 2 ) {
            return tmpFile.getName().substring(0, whereDot);
            //extension = filename.substring(whereDot+1);
        }
        return "";
    }
    /**
     * 
     * @param fileName
     * @return File path without the file's name's extension
     */
    public String GetFilePathWithoutExtension(String fileName)
    {
        File tmpFile = new File(fileName);
        tmpFile.getPath();
        int whereDot = tmpFile.getPath().lastIndexOf('.');
        if (0 < whereDot && whereDot <= tmpFile.getPath().length() - 2 ) {
            return tmpFile.getPath().substring(0, whereDot);
            //extension = filename.substring(whereDot+1);
        }
        return "";
    }
    /**
     * Reads the specified text file, and then writes the read text
     * into the specified JTextPane.
     *
     * @param TextPane
     * @param file
     */
    public void ReadFileWriteTextField(SweTextPane TextPane, File file)
    {
        
//              BufferedReader br = new BufferedReader(new FileReader(file));
//              String s=""; int c=0;
//              while((c=br.read())!=-1) s+=(char)c;
//
//              br.close();
        if(TextPane != null)
            TextPane.setText(ReadFileGetText(file));
        else
            JOptionPane.showMessageDialog(null,"SweTextPane component is null! ","Component error",JOptionPane.ERROR_MESSAGE);
    }
    public void ReadFileWriteTextField(JTextPane TextPane, File file)
    {

//              BufferedReader br = new BufferedReader(new FileReader(file));
//              String s=""; int c=0;
//              while((c=br.read())!=-1) s+=(char)c;
//
//              br.close();
        if(TextPane != null)
            TextPane.setText(ReadFileGetText(file));
        else
            JOptionPane.showMessageDialog(null,"SweTextPane component is null! ","Component error",JOptionPane.ERROR_MESSAGE);
    }
    /**
     * Creates a file which is specified by its full path.
     *
     * @param FilePath
     * @throws java.io.IOException
     */
    private void CreateFile(String FilePath)
    {
        try
        {
            File file = new File(FilePath);

            boolean success = file.createNewFile(); // Create file if it does not exist

            if (!success) //If the file exists
            {
                DeleteFile(FilePath);
                CreateFile(FilePath);
            }
        }
        catch (IOException ex)
        {
            JOptionPane.showMessageDialog(null,"Cannot create XML file! " + ex.getMessage(),"File error",JOptionPane.ERROR_MESSAGE);
        }
    }
    /**
     * Writes a string value into a file. The file needs to be specifed
     * by its full path.
     *
     * @param FileName
     * @param Value
     * @throws java.io.IOException
     */
    public void WriteIntoFile(String FileName, String Value)
    {
        CreateFile(FileName);

        FileOutputStream fos;
        DataOutputStream dos;

        try
        {
              File file= new File(FileName);
              fos = new FileOutputStream(file);
              dos=new DataOutputStream(fos);

              dos.writeBytes(Value);
        }
        catch (IOException ex)
        {
            JOptionPane.showMessageDialog(null,"Cannot write into XML file! " + ex.getMessage(),"File error",JOptionPane.ERROR_MESSAGE);
        }
    }
}
